from app.extensions import db
from flask import request
from datetime import datetime
from app.models.model_mixin import BaseMixin


# article model
class Article(db.Model, BaseMixin):
    """params: status 9:默认 0:回收站
    """
    id = db.Column(db.Integer, primary_key=True)
    cid = db.Column(db.Integer, db.ForeignKey('category.id'))
    uid = db.Column(db.Integer, db.ForeignKey('user.id'))
    thumb = db.Column(db.String(255))
    title = db.Column(db.String(255))
    content = db.Column(db.Text)
    status = db.Column(db.Integer, default=9, index=True)
    url = db.Column(db.String(255))
    created_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow)

    user = db.relationship('User', back_populates='articles')
    category = db.relationship('Category', back_populates='articles')

    def to_dict(self):
        res_data = {
            'id': self.id,
            'thumb': self.thumb,
            'title': self.title,
            'author': self.author,
            'status': self.status,
            'url': self.url,
            'created_at': self.created_at,
        }
        if 'category' in request.args.get('expand', ''):
            res_data.update({
                'category': {
                    'id': self.category.id,
                    'title': self.category.title
                }
            })
        return res_data

    @staticmethod
    def to_collection_dict(query, page, per_page=10):
        resources = query.paginate(page, per_page, False)
        data = {
            'items': [item.to_dict() for item in resources.items],
            '_meta': {
                'page': page,
                'per_page': per_page,
                'total_pages': resources.pages,
                'total_items': resources.total
            }
        }
        return data
